URL 관련 클래스 II - WebSpiderWithURLConnection.java :: 자주 쓰이는 메소드및 API 를 정리합니다.[SSISO Community]
 
SSISO 카페 SSISO Source SSISO 구직 SSISO 쇼핑몰 SSISO 맛집
추천검색어 : JUnit   Log4j   ajax   spring   struts   struts-config.xml   Synchronized   책정보   Ajax 마스터하기   우측부분

자주 쓰이는 메소드및 API 를 정리합니다.
[1]
등록일:2008-03-09 14:31:16 (0%)
작성자:
제목:URL 관련 클래스 II - WebSpiderWithURLConnection.java


URLConnection

  

아래는  URLConnnection을  이용해서  URL  주소의  내용을  읽어오는  방법을  순서대로  나열해  보았습니다.

1.  URL  객체  생성

2.  URL  객체의  openConnection()  메소드를  호출해서  URLConnection  객체를  획득

3.  URLConnection의  getInputStream()  메소드를  호출해서  URL  주소의  내용을  읽어  들이는  InputStream  객체를  획득

4.  InputStream을  이용해서  URL  주소의  내용을  읽음

  

WebSpiderWithURLConnection.java

import  java.net.*;
import  java.io.*;

public  class  WebSpiderWithURLConnection  {
    public  static  void  main(String[]  args)  {
        if(args.length  !=  2)  {
            System.out.println("사용법  :  java  WebSpider  URL  filename");
            System.exit(1);
        }

        URL  url  =  null;

        try  {
            url  =  new  URL(args[0]);
        }  catch  (MalformedURLException  e1)  {
            System.out.println("잘못된  URL  형식입니다.");
            System.out.println(e1);
            System.exit(1);
        }

        FileOutputStream  fos  =  null;

        try  {
            URLConnection  urlcon  =  url.openConnection();
            String  contentType  =  urlcon.getContentType();
            long  d1  =  urlcon.getDate();
            java.util.Date  d  =  new  java.util.Date(d1);
            java.text.SimpleDateFormat  format  =  new  java.text.SimpleDateFormat("yyyy-MM-dd  HH:mm:ss  a");
            String  sdate  =  format.format(d);
            System.out.println("Content  Type  :  "  +  contentType);
            System.out.println("읽기  시작한  시간  :  "  +  sdate);

      
            InputStream  in  =  urlcon.getInputStream();
            fos  =  new  FileOutputStream(args[1]);
            byte[]  buffer  =  new  byte[512];
            int  readcount  =  0;
            System.out.println("\n읽어오기  시작합니다  ...\n");

            while((readcount  =  in.read(buffer))  !=  -1)  {  
                fos.write(buffer,  0,  readcount);
            }

            System.out.println(args[1]  +  "  파일에  저장되었습니다.");
        }  catch(Exception  ex)  {
            System.out.println(ex);
        }  finally  {
            try  {
                if(fos  !=  null)  fos.close();
            }  catch(Exception  e)  {}
        }
    }
}

  

-  URLConnection은  URL  주소의  내용을  읽어오거나  반대로  URL  주소가  가리키는  웹애플리케이션(CGI,  Servlet,  JSP  등)에게  GET  방식이나  POST  방식으로  추가적인  정보를  전달할  수  있습니다.  그리고  페이지의  내용을  읽어오는  것  외에도  반대로  웹애플리케이션에  추가적인  정보를  전달해야  할  때가  있는데  이때  POST  방식을  사용하게  됩니다.
[본문링크] URL 관련 클래스 II - WebSpiderWithURLConnection.java
[1]
코멘트(이글의 트랙백 주소:/cafe/tb_receive.php?no=2419
작성자
비밀번호

 

SSISOCommunity

[이전]

Copyright byCopyright ⓒ2005, SSISO Community All Rights Reserved.